package com.iflytek.cosmo.ocr.service.impl;

import com.google.common.collect.Lists;
import com.iflytek.cosmo.ocr.common.constant.AbstractExceptionCodeConstant;
import com.iflytek.cosmo.ocr.common.constant.AbstractExceptionDescribeConstant;
import com.iflytek.cosmo.ocr.common.constant.AbstractPathConstant;
import com.iflytek.cosmo.ocr.common.constant.AbstractVersionUpdateStatusConstants;
import com.iflytek.cosmo.ocr.common.exception.ParseDownLoadUrlExceptionAbstract;
import com.iflytek.cosmo.ocr.common.exception.VersionSetupOutputExceptionAbstract;
import com.iflytek.cosmo.ocr.dao.VersionInfoDao;
import com.iflytek.cosmo.ocr.dao.VersionSetupDao;
import com.iflytek.cosmo.ocr.model.domain.PropertySources;
import com.iflytek.cosmo.ocr.model.domain.VersionSetupOutput;
import com.iflytek.cosmo.ocr.model.entity.VersionInfoEntity;
import com.iflytek.cosmo.ocr.model.entity.VersionSetupEntity;
import com.iflytek.cosmo.ocr.service.SettingService;
import com.iflytek.cosmo.ocr.service.VersionSetupService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class VersionSetupServiceImpl implements VersionSetupService {
    /**
     * 日志记录器
     */
    private Logger logger = LoggerFactory.getLogger(VersionSetupServiceImpl.class);

    /**
     * 版本基础信息配置信息dao
     */
    @Autowired
    private VersionInfoDao versionInfoDao;

    /**
     * 版本详细配置信息dao
     */
    @Autowired
    private VersionSetupDao versionSetupDao;

    /**
     * 获取下载绝对路径接口
     */
    @Autowired
    private SettingService settingService;

    /**
     * 查询配置表
     *
     * @param projectName 客户端updateConfig.cfg 中的appName
     * @param projectProfile 和客户端约定的版本描述名称
     * @param type
     * @return
     */
    public List<VersionSetupEntity> queryVersionSetupList(String projectName, String projectProfile, Integer type) {

        // 查询版本信息基础配置唯一标识id
        VersionInfoEntity versionInfoEntity = new VersionInfoEntity();
        versionInfoEntity.setProjectName(projectName);
        versionInfoEntity.setProjectProfile(projectProfile);
        VersionInfoEntity versionInfo = versionInfoDao.selectOne(versionInfoEntity);
        List<VersionSetupEntity> versionList = null;
        if (versionInfo != null) {
            String versionId = versionInfo.getId();
            // 查询版本详细配置
            VersionSetupEntity versionSetupEntity = new VersionSetupEntity();
            versionSetupEntity.setVersionId(versionId);
            versionSetupEntity.setType(type);
            versionList = versionSetupDao.select(versionSetupEntity);
        }

        return versionList;
    }

    /**
     * 版本配置
     *
     * @param projectName 客户端updateConfig.cfg 中的appName
     * @param projectProfile 和客户端约定的版本描述名称
     * @return
     * @author xqxia3
     * @throws VersionSetupOutputExceptionAbstract
     * @date 2018年4月23日
     */
    @Override
    public VersionSetupOutput queryUpgradeVersionSetup(String projectName, String projectProfile)
            throws VersionSetupOutputExceptionAbstract, ParseDownLoadUrlExceptionAbstract {
        // 查询版本配置信息
        List<VersionSetupEntity> list = queryVersionSetupList(projectName, projectProfile, 0);

        if (CollectionUtils.isEmpty(list)) {
            // 获取版本配置信息失败自定义异常
            logger.error("projectName:{}, projectProfile:{}, 异常VersionSetupOutputException:{}", projectName,
                    projectProfile, AbstractExceptionDescribeConstant.VERSION_UPGRADE_EXCEPTION);
            throw new VersionSetupOutputExceptionAbstract("异常代码:" + AbstractExceptionCodeConstant.TARGET_NOT_EXIST_EXCEPTION_CODE);
        }

        // 版本配置信息输出对象
        VersionSetupOutput versionSetupOutput = new VersionSetupOutput();
        versionSetupOutput.setName(projectName);

        List<String> profileList = Lists.newArrayList(projectProfile);
        versionSetupOutput.setProfiles(profileList);
        // 版本下载配置信息map封装
        HashMap<String, Object> source = new HashMap<String, Object>();
        for (VersionSetupEntity vs : list) {
            if (AbstractPathConstant.DOWNLOAD_URL_KEY.equals(vs.getKey())) {
                // 版本下载地址,需要系统配置路径+数据库配置的文件相对路径
                String PackageAbsoluteUrl = settingService.getPackageAbsoluteUrl(vs.getValue());
                source.put(vs.getKey(), PackageAbsoluteUrl);
            } else if (vs.getKey().equals(AbstractVersionUpdateStatusConstants.FORCE_UPDATE_NAME)) {
                // 强制更新状态字符型改成Boolean型 true强制更新   false不强制更新
                source.put(vs.getKey(), AbstractVersionUpdateStatusConstants.FORCE_UPDATE.equals(vs.getValue()));
            } else {
                source.put(vs.getKey(), vs.getValue());
            }
        }
        PropertySources propertySources = new PropertySources();
        // 版本配置名称  //projectName+"/"+projectProfile
        propertySources.setName(String.format("%s/%s",projectName,projectProfile));
        // 版本配置详细信息
        propertySources.setSource(source);
        List<PropertySources> propertySourceList = Lists.newArrayList(propertySources);

        versionSetupOutput.setPropertySources(propertySourceList);

        return versionSetupOutput;
    }

    /**
     * 运行配置
     *
     * @param projectName
     * @param projectProfile
     * @return
     * @author xqxia3
     * @date 2018年4月23日
     */
    @Override
    public VersionSetupOutput queryRunningVersionSetup(String projectName, String projectProfile)
            throws VersionSetupOutputExceptionAbstract {
        // 查询版本配置信息
        List<VersionSetupEntity> list = queryVersionSetupList(projectName, projectProfile, 1);
        if (CollectionUtils.isEmpty(list)) {
            // 获取版本配置信息失败自定义异常
            logger.error("projectName:{}, projectProfile:{}, 异常VersionSetupOutputException:{}", projectName,
                    projectProfile, AbstractExceptionDescribeConstant.VERSION_RUNNING_EXCEPTION);
            throw new VersionSetupOutputExceptionAbstract("异常代码:" + AbstractExceptionCodeConstant.TARGET_NOT_EXIST_EXCEPTION_CODE);
        }

        // 版本配置信息输出
        VersionSetupOutput versionSetupOutput = new VersionSetupOutput();
        versionSetupOutput.setName(projectName);
        List<String> profileList = new ArrayList<String>();
        profileList.add(projectProfile);
        versionSetupOutput.setProfiles(profileList);

        HashMap<String, String> source = new HashMap<String, String>();
        for (VersionSetupEntity vs : list) {
            source.put(vs.getKey(), vs.getValue());
        }
        PropertySources propertySources = new PropertySources();
        //projectName+"/"+projectProfile
        propertySources.setName(String.format("%s/%s",projectName,projectProfile));
        List<PropertySources> propertySourceList = Lists.newArrayList(propertySources);
        propertySourceList.add(propertySources);
        versionSetupOutput.setPropertySources(propertySourceList);

        return versionSetupOutput;
    }

}
